package com.abc.cloud.service.impl;

import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.common.utils.StringUtil;
import com.abc.cloud.service.EmailService;
import com.abc.cloud.vo.mail.MailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

import static com.abc.cloud.common.constants.Constants.*;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送验证码
     * @param title
     * @param content
     * @param from
     * @param to
     */
    public void send(String title, String content, String from, String to){
        try{
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            mimeMessageHelper.setFrom(MAIL_FROM + "(" + from + ")");
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(title);
            //  true表示支持html格式
            mimeMessageHelper.setText(content, true);
            // 发送邮件
            javaMailSender.send(mimeMessage);
        } catch (Exception e){
            throw new MyException("发送邮箱出错，请正确输入");
        }
    }

    @Override
    public Boolean sendCode(String mail, String username) {
        String code = StringUtil.generateRandomString(6);
        String key = SEND_MAIL + username + ":" + mail;
        String find = redisTemplate.opsForValue().get(key);
        if (find != null){
            return false;
        }

        redisTemplate.opsForValue().set(key, code, 3, TimeUnit.MINUTES);
        send(REGISTER_TITLE, REGISTER_CONTENT.replace("666666", code), MAIL_FROM, mail);
        return true;
    }
}
